/**
 * Created by shenhai on 15/9/16.
 */

var async = require('async');
var Community = mongoose.model('community');
var User = mongoose.model('user');
var UserAuthentication = mongoose.model('user_authentications');
var toolUtil = require('../../../common/utils/toolUtil');

exports.authListService = function (req ,callback) {


    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;

    var nickName = body.nickName;
    var sortType = {dateCreated: -1};


    var option = body;
    delete option.nickName;

    async.series([

        function (callbackInner) {

            if (nickName) {

                var temp = {nickName: new RegExp(nickName)};
                User.find(temp, "_id").exec(function (err, result) {

                    var userIds = new Array();
                    for (var i = 0; i < result.length; i++) {
                        userIds[i] = result[i];
                    }
                    option.user = {$in: userIds};
                    callbackInner(err, result);
                })
            }else {
                callbackInner();
            }
        },

        function (callbackInner) {

            UserAuthentication.count(option, function (err, count) {
                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },

        function (callbackInner) {

            UserAuthentication.find(option, 'isValid user community imageURL promotionCode status dateCreated').skip(index).limit(size)
                .populate('user', '_id nickName images roomUnit roomNumber')
                .populate('community', '_id communityName').sort(sortType).exec(function (err, result) {

                    result.forEach(function (entity) {
                        if (entity.imageURL) {
                            entity.imageURL = 'http://' + imgHost +  entity.imageURL;
                        }
                    });

                    callbackInner(err, result)

                });
        },
    ], callback);
};



// V认证 通过/取消认证
exports.authenticateService = function (req, callback) {
    var communityId;
    var huanxinUser;

    var body = req.body;

    logger.debug(body);

    UserAuthentication.findOne({user: body.user, community: body.community, isValid: true}, function (err, result) {
        if (body.status && result.status) {
            var message = {
                message: '已经通过认证'
            };
            callback(message, null);
        } else {
            async.series([
                function (callbackInner) {
                    UserAuthentication.update({
                        'user': body.user,
                        'community': body.community,
                        isValid: true
                    }, {'status': body.status}, callbackInner);
                },
                function (callbackInner) {
                    User.findOne({_id: body.user}, 'community huanxinUserName nickName images invitedBy').populate('community', '_id communityName').exec(function (err, user) {
                        if (user) {
                            communityId = user.community._id;
                            huanxinUser = user;
                            callbackInner(null, user.invitedBy);
                        }else {
                            callbackInner();
                        }
                    });
                },
                function (callbackInner) {


                    logger.debug(3);


                    if (body.community == communityId) {
                        User.update({_id: body.user}, {'authenticationStatus': body.status}, callbackInner);
                        toolUtil.setUserByToken(body.user);
                    } else {
                        callbackInner(null, null);
                    }
                },
                function (callbackInner) {

                    logger.debug(4);

                    if (body.status && body.community == communityId) {

                        var message = "你好，你的V认证已经通过，我们将为V用户提供更多，更好的服务，也让你在小区中更与众不同。"
                        toolUtil.pushCustomerServiceMessage(huanxinUser, message);
                        callbackInner(null, null);
                    } else {
                        callbackInner(null, null);
                    }
                },

                function (callbackInner) {

                    logger.debug(5);

                    if (body.community == communityId) {
                        var status = 0;
                        if (body.status) {
                            status = 1;
                        } else {
                            status = 2;
                        }
                        //个推
                        var content = {
                            f: 3,
                            vStatus: status
                        };
                        var pushData = {
                            uList: [body.user],
                            content: content
                        };

                        logger.debug(pushData);
                        toolUtil.putMessageTransmissionPushMQ(pushData);
                    };
                    callbackInner(null, null);
                },
                //更新最后修改日期
                function (callbackInner) {

                    logger.debug(6);

                    UserAuthentication.update({
                        'user': body.user,
                        'community': body.community
                    }, {dateLastModified: new Date()}, callbackInner);
                },
                function (callbackInner) {

                    logger.debug(7);

                    toolUtil.setUserByToken(body.user);
                    callbackInner();
                }
            ], callback);
        }
    });
};


// V认证--拒绝
exports.refuseAuthenticateService = function (req, callback) {

    var communityId;
    var huanxinUser;

    var body  = req.body;
    var id = body.id;

    logger.debug(body);

    if (!(id && body.userId && body.community && body.reason)) return callback('缺少refuse id/reason', null);

    async.series([
        function (callbackInner) {
            UserAuthentication.update({_id: id}, {isValid: false, refusalReason: body.reason}, callbackInner);
        },
        function (callbackInner) {

            User.findOne({_id: body.userId}, 'huanxinUserName community nickName images').populate('community', '_id communityName').exec(function (err, result) {
                communityId = result.community._id;
                huanxinUser = result;
                callbackInner(null, null);
            });
        },
        function (callbackInner) {
            if (body.community == communityId) {

                var message = body.reason;
                toolUtil.pushCustomerServiceMessage(huanxinUser, message);
            }
            callbackInner(null, null);
        },
        function (callbackInner) {
            if (body.community == communityId) {
                //个推
                var content = {
                    f: 3,
                    vStatus: 0
                };
                var pushData = {
                    uList: [body.userId],
                    content: content
                };
                toolUtil.putMessageTransmissionPushMQ(pushData);
            }
            callbackInner(null, null);
        }
    ], callback);
};



